/////////////////////////////////////////////////////////////////////////
//
// Amuse Engine SDK - core/threads
// Copyright (c) 2014.  All Rights Reserved
//
// File:		AEThread_win32.cpp
// Author:		Gianluca Belardelli
// Date:		08/10/2013
//
/////////////////////////////////////////////////////////////////////////
#ifndef WIN32
#error "Errore! Il file contiene codice specifico per Win32"
#endif

#include <AECore.h>
#include <core\threads\AEThread.h>

AEThread::AEThread( void )
{
	m_lpThread = NULL;
	m_uiThreadID = 0;
}

AEThread::~AEThread( void )
{
	if( m_lpThread )
		CloseHandle( m_lpThread );
}

AEINT32 AEThread::StartThread( AEStartFunction *lpfnFunction, void *lpParam, const char *lpName, int nThreadStackSize )
{
    m_lpThread = ::CreateThread
                  (
                    NULL,
                    nThreadStackSize,
                    (LPTHREAD_START_ROUTINE)lpfnFunction,
                    lpParam,
                    0,
                    &m_uiThreadID
                  );

	if( m_lpThread )
		return m_uiThreadID;

	return -1;
}

void AEThread::JoinThread( void )
{
	AEASSERT_MSG( m_lpThread != NULL, "Thread non inizializzato" );

	switch ( WaitForSingleObject( m_lpThread, INFINITE ) )
	{
		case WAIT_OBJECT_0:
			CloseHandle( m_lpThread );
			m_lpThread = NULL;
			m_uiThreadID = 0;
			return;
	}
}

AEThread::AEThreadStatus AEThread::GetStatus( void ) const
{
	if( m_uiThreadID == 0 )
		return AEThread::AEThreadStatus::AETHREAD_NOT_STARTED;

	return AEThread::AEThreadStatus::AETHREAD_RUNNING;
}

AETHREADHANDLE AEThread::GetThreadHandle( void ) const
{
	return m_lpThread;
}

